﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace Planetwork
{
    public partial class AddPics : System.Web.UI.Page
    {
        static string conStr = ConfigurationManager.AppSettings["conStr"];
        SqlConnection mycon = new SqlConnection(conStr);
        protected void Page_Load(object sender, EventArgs e)
        {
             
            if(!IsPostBack)
            {
                if (Request.QueryString["index"] == null || Context.Session["name"] == null)
                {
                    Response.Redirect("../Login/Login.aspx?ReturnUrl=" + Request.RawUrl);
                }
                this.name.Text = Session["name"].ToString();
                this.remarks.Text = "";
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {

            HttpPostedFile image = this.imageUpload.PostedFile;
            int length = image.ContentLength;
            if(length < 1)
            {
                Response.Write("<script>alert('请选择图片!');</script>");
                return;
            }
            byte[] buffer = new byte[length];
            string imageType = image.ContentType;
            Stream stream = image.InputStream;
            stream.Read(buffer, 0, length);

            string sql = "insert into Images (Author, ImageData, ImageMimeType, Remarks, ParentID) values(@author, @image, @imageType, @remarks, @parentID)";
            string t = this.remarks.Text;
            SqlCommand mycmd = new SqlCommand(sql, mycon);
            mycmd.Parameters.AddWithValue("@author", Session["name"].ToString());
            mycmd.Parameters.AddWithValue("@image", buffer);
            mycmd.Parameters.AddWithValue("@imageType", imageType);
            mycmd.Parameters.AddWithValue("@remarks", this.remarks.Text);
            mycmd.Parameters.AddWithValue("@parentID", Convert.ToInt32(Request.QueryString["index"]));

            mycon.Open();

            try
            {
                mycmd.ExecuteNonQuery();
                mycon.Close();
                this.remarks.Text = "";
                Response.Write("<script>alert('添加成功!');</script>");
            }
            catch(Exception ex)
            {
                mycon.Close();
                string error = "上传出错: " + ex.ToString();
                Response.Write("<script>alert('" + error + "');</script>");
            }
        }
    }
}